package situ.com.androidstudy;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by Gao on 2021/10/26.
 */

public class FileActivity extends Activity {
    private ListView listView;
    private FileAdapter fileAdapter;
    // 记录当前的目录
    private File currentDirectoryFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);

        listView = (ListView) findViewById(R.id.listView);
        // 判断有没有sdcard卡
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, "没有sdcard卡", Toast.LENGTH_SHORT).show();
            return;
        }
        // 返回sdcard的根目录
        currentDirectoryFile = Environment.getExternalStorageDirectory();
        // 列出来当前文件夹下面所有的文件（包含目录）
        File[] files = currentDirectoryFile.listFiles();
        fileAdapter = new FileAdapter(files);
        listView.setAdapter(fileAdapter);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (currentDirectoryFile.equals(Environment.getExternalStorageDirectory())) {
                // 当前已经是sdcard的根目录，即使按了back键也不需要回退，直接关闭这个Activity
                setResult(RESULT_CANCELED);
                // 销毁Activity
                finish();
                return true;
            }

            // 返回上一层目录
            String parentPath = currentDirectoryFile.getParent();
            // 更新当前的目录为上一层目录
            currentDirectoryFile = new File(parentPath);
            fileAdapter.setData(currentDirectoryFile.listFiles());
            fileAdapter.notifyDataSetChanged();

            return true;
        }


        return super.onKeyDown(keyCode, event);
    }

    private class FileAdapter extends BaseAdapter {
        // java里面不管文件夹还是文件都是用File来表示
        private File[] files;

        public FileAdapter(File[] files) {
            this.files = files;
        }

        public void setData(File[] files) {
            this.files = files;
        }

        @Override
        public int getCount() {
            return files.length;
        }

        @Override
        public Object getItem(int position) {
            return files[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = layoutInflater.inflate(R.layout.file_list_item, null);
                viewHolder.fileIconImageView = (ImageView) convertView.findViewById(R.id.iv_file_icon);
                viewHolder.fileNameTextView = (TextView) convertView.findViewById(R.id.tv_file_name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            final File file = files[position];
            String fileName = file.getName();
            viewHolder.fileNameTextView.setText(fileName);
            if (file.isDirectory()) {
                viewHolder.fileIconImageView.setBackgroundResource(R.drawable.folder);
            } else {
                viewHolder.fileIconImageView.setBackgroundResource(R.drawable.file);
            }

            convertView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (file.isDirectory()) {// 点击的是目录
                        // 列出点击的目录下面所有的文件
                        File[] files = file.listFiles();
                        // view-data绑定的过程已经完成，现在只需要更新数据
                        fileAdapter.setData(files);
                        fileAdapter.notifyDataSetChanged();
                        currentDirectoryFile = file;
                    } else if (file.isFile() && file.getName().endsWith(".mp3")) {// 如果是mp3，那么就交给音乐播放器去播放
                       /* Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
                        intent.putExtra("path", file.getPath());
                        ArrayList<String> mp3List = getMp3List(files);
                        intent.putExtra("mp3List", mp3List);
                        startActivity(intent);*/
                    } else {
                        // 非mp3的普通文件
                        // Toast.makeText(MainActivity.this, "不支持改类型文件", Toast.LENGTH_SHORT).show();
                    }
                }

                //返回所有以mp3为结尾的文件的路径
                private ArrayList<String> getMp3List(File[] files) {
                    ArrayList<String> list = new ArrayList<String>();
                    for (File file : files) {
                        if (file != null && file.isFile() && file.getName().endsWith(".mp3")) {
                            list.add(file.getPath());
                        }
                    }
                    return list;
                }
            });

            return convertView;
        }

        private class ViewHolder{
            public ImageView fileIconImageView;
            public TextView fileNameTextView;
        }

    }


}